package fanxing.lianxi.deno06;

import java.util.Arrays;

/*
* 模拟实现 ArrayList
* */
public class MyArrayList<E> {
    //数据封装容量
    private static final  int DEFAUL_CAPCINY = 10;
    //存放实际用的容量
    private Object[] emledate = {};
    //数组初始话容量
    private int size;

    /*
    * 缺省构造方法 -- 实例化一个数组 -- 默认值为 10*/
    public MyArrayList() {
       this.emledate = new Object[DEFAUL_CAPCINY];
    }
    /*
    * 重载构造方法 -- 实例化一个数组 ，大小由用户决定*/
    public MyArrayList(int size) {
        this.emledate = new Object[size];
    }
    /*
    * 添加元素
    * */
    public boolean add (E e){
        //判断是否扩容
        grow();
        //添加元素
        this.emledate[size] = e;
        size ++ ;
        return true;
    }

    /*
    *实现数组扩容*/
    private void grow() {
        if (size == this.emledate.length){
            this.emledate = Arrays.copyOf(this.emledate, emledate.length * 2);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for(Object element : this.emledate){
            sb.append(element).append(",");
        }
        sb.setCharAt(sb.length() - 1,']');
        return sb.toString();
    }
    /*
    * 通过下标删除 */
    public E remoay(int index){
        checkIndex(index);
        //合法验证
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("下标索引超出范围" + index);
        }
        //获取删除的元素
        E oldElement = (E)this.emledate[index];
        //删除元素
        System.arraycopy(this.emledate ,index + 1, this.emledate, index,this.emledate.length - index - 1);

        //最后一个元素设置为null
        this.emledate[size - 1] = null;
        //更新实际大小
        size --;
        return oldElement;
    }
    /*
    * 返回数组实际的容量*/
    public int size(){
        return this.size;
    }
    /*
    * 判断数组是否为空*/
    public boolean isEmgty(){
        return this.size == 0;
    }
    /*
    * 给集合某个下标设置元素
    * */
    public E set(int index,E element){
        checkIndex(index);
        Object object = this.emledate[index];
        this.emledate[index]=element;
        return (E) object;
    }

    /*
    * 获取集合下标对应的元素
    * */
    public E get(int index){
        checkIndex(index);
        return (E) this.emledate[index];
    }

    /*
    * 检查下标是为越界*/
    private void checkIndex(int index) {
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("下标索引超出范围" + index);
        }
    }
}
